<?php

/*
	Class: Role

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>

	About: See Also
		<Cts_Controller_Action_Abstract>
*/
class RoleController extends Cts_Controller_Action_Admin {

	/* Group: Instance Methods */

	/*
		Function: init
			Invoked automatically when an instance is created.
			Initializes the current instance.
			Also initializes the parent object (calls init() on the parent instance).
	*/
    function init() {
        parent::init();
    }

	/* Group: Actions */

	/*
		Function: index
			Description of what this action does.

		View Variables:
			roles - array containing all roles from the db. Uses <RolesIndex> view.
			
	*/
    function indexAction() {
        $roles_index_table = new RolesIndex();             	
        $this->view->roles = $roles_index_table->fetchAll()->toArray();
    }

	/*
		Function: edit
			Creates or edits roles.

		HTTP GET or POST Parameters:
			param - description of param

		Registry Values:
			registry_value - description of registry value used in this action

		Plugin Hooks:
			- *hook_name* (filter|action) - description of when hook is called
				param param_name - description of param passed to hook

		View Variables:
			$view_var - Description of variable that gets passed to view
			
	*/
    function editAction() {
		$request = new Cts_Request($this->getRequest());
		$roles_table = new Roles();
		
		$role_choices = array();
		$role_choices['-1'] = "none";

		if ($this->getRequest()->isPost()) {
            
            $errors = array();		  
		    
            if ($request->has('shortname')) {
              $shortname = $request->shortname;
              if (!Cts_Validate::checkLength($request->shortname, 1, 255)) {
                $errors[] = $this->_T("Shortname must be between 1 and 255 chars.");
              }
            } else {
              $errors[] = $this->_T("Shortname is a requried field.");
            }

			$description = $request->description;
			$inherits_id = $request->inherits_id;
			$isadmin = (int)$request->checkbox('isadmin');
			$isguest = (int)$request->checkbox('isguest');
			$isdefault = (int)$request->checkbox('isdefault');
			if (count($errors) == 0) {
				$data = array(
					'shortname' => $shortname,
					'description' => $description,
					'isadmin' => $isadmin,
					'isguest' => $isguest,
					'isdefault' => $isdefault,
				);
				if ($inherits_id != -1) {
					$data['inherits_id'] = $inherits_id;
				} else {
					$data['inherits_id'] = null;
				}
				//If we have an id, this is an update.
				$id = (int)$this->_request->getPost('id');
				if ($id != 0) {
					$where = 'id = ' . $id;
					$roles_table->update($data, $where);
				} else {
					//We don't, this is an insert.
					$roles_table->insert($data);
				}
				$this->_redirect('/role');				
			} else {
			  $this->view->errors = $errors;
			}
		}
		
		if ($request->has('id')) {
			// this is an edit
			$id = $request->id;
			if ($id > 0) {
				$this->view->role = $roles_table->fetchRow('id = ' . $id)->toArray();
			}
			foreach ($roles_table->fetchAll('id <> ' . $id)->toArray() as $role) {
				$role_choices[$role['id']] = $role['shortname'];
			}
			$this->view->role_choices = $role_choices;
		} else {
			
			foreach ($roles_table->fetchAll()->toArray() as $role) {
				$role_choices[$role['id']] = $role['shortname'];
			}			
			$this->view->role_choices = $role_choices;
		}
		
    }        

	/*
		Function: delete
			Delete a role.
			
		HTTP POST Parameters:
			delete - Value must be yes or this doesn't work.
			id - The id of the role we're editing (mainly for redirect purposes).

		View Variables:
			role - array containing the role
			success - success message, if any
			errors - array of error messages, if any			
	*/
	function deleteAction(){
		$request = new Cts_Request($this->getRequest());
		$roles_table = new Roles();
		
		if($request->has('id')){
		  $id = $request->id;
		  $role = $roles_table->fetchRow("id = ".$id);
		  if(is_null($role)){
		    $this->_redirect('/role');
		  }
		} else {
		  $this->_redirect('/role');
		}
        
		if ($this->getRequest()->isPost() and $request->has("delete")) {

		  $errors = array();

		  // can't be admin
		  if ((boolean)$role->isadmin) {
		    $errors[] = $this->_T("This is the admin role. It cannot be deleted.");
		  }

		  // can't be guest
		  if ((boolean)$role->isguest) {
		    $errors[] = $this->_T("This is the guest role. It cannot be deleted.");
		  }
		  
		  // can't be default
		  if ((boolean)$role->isdefault) {
		    $errors[] = $this->_T("This is the default role. It cannot be deleted.");
		  }

		  // can't have children
		  $where = "inherits_id = ".$role->id;
		  $inheritied_by = $roles_table->fetchAll($where);
		  if(count($inheritied_by) > 0){
		    $error = $this->_T("This role is inherited by role(s) ");
		    $firstpass = true;
		    
		    foreach($inheritied_by as $role_i){
		      if($firstpass){
		        $firstpass = false;
		      } else {
		        $error .= ", ";
		      }
		      $error .= $role_i->shortname;
		      
		    }
		    $error .= $this->_T(". It cannot be deleted.");

		    $errors[] = $error;
		  }

			if ($request->delete == "Yes") {
				if (count($errors) > 0) {
					$this->view->errors = $errors;
				} else {
					$roles_table->delete("id = ".$id);
					$this->view->success = $this->_T("Role deleted.");
				}
			} else {
				$this->_redirect("/role");
			}
		}
		$this->view->role = $role->toArray();
		
	}    

}
